package cc.cinemate.api;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.simpleframework.xml.transform.Matcher;
import org.simpleframework.xml.transform.Transform;

public class DateMatcher implements Matcher, Transform<Date> {

	public Transform match(Class type) throws Exception {
		if (type == Date.class) {
			return this;
		}
		return null;
	}

	public Date read(String value) throws Exception {
		Date result = new Date(1, 1, 1);
		if (value != null) {
			if (value.equals("[[NULL]]")) {
				return null;
			}
			if (value.equals("[[EMPTY]]")) {
				return result;
			}
		}
		try{
			result = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(value);
		} catch(ParseException e0){
			try{
				result = new SimpleDateFormat("yyyy-MM-dd").parse(value);
			} catch(ParseException e1){
				//DO NOTHING
			}
		}
		return result;
	}

	public String write(Date value) throws Exception {
		if (value == null) {
			return "[[NULL]]";
		}
		if (value.equals("")) {
			return "[[EMPTY]]";
		}
		return value.toString();
	}
}
